<?php
declare(strict_types=1);

namespace Modules\Customer\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Customer\Models\Customer;
use Illuminate\Http\Request;
use Modules\CustomerLesson\Models\CustomerLesson;
use Modules\LessonHour\Http\Controllers\LessonHourController;
use Modules\LessonHour\Models\LessonHour;


class CustomerController extends Controller
{
    public function __construct(
        protected readonly Customer $model
    ){}

    /**
     * @return mixed
     */
    public function index(Request $request): mixed
    {
        $where = [];
        $param = $request->all();

        $where['customer.status'] = 1;
        $param['user_name'] = $param['user_name'] ?? '';

        // 分场景统计
        if (!empty($param['teacher_id']))
        {
            $where['customer_lesson.teacher_id'] = $param['teacher_id'];
            $result = Customer::query()
                ->where($where)
                ->where("customer.username","like","%{$param['user_name']}%")
                ->select(['customer.id as id','customer.username as customer_name','customer.phone','customer_lesson.lessons','customer.created_at'])
                ->join("customer_lesson","customer.id","=","customer_lesson.customer_id","left")
                ->join("teacher","customer_lesson.teacher_id","=","teacher.id","left")
                ->paginate($param['limit'] ?? 10 ,['*'] ,'' ,$param['page'])->toArray();

            if (!empty($result['data']))
            {
                $customerIds = [];
                foreach ($result['data'] as $key => $value)
                {
                    $customerIds[] = $value['id'];
                    $result['data'][$key]['customer_number'] = 100 . $value['id'];
                    $result['data'][$key]['is_customer'] = true;
                    $result['data'][$key]['last_lessons'] = $value['lessons'];
                }

                $lessonStatus= [LessonHourController::LESSON_STATUS_2,LessonHourController::LESSON_STATUS_5];
                $lessonHours = LessonHour::query()
                    ->whereIn("lesson_hour.customer_id",$customerIds)
                    ->whereIn('lesson_hour.lesson_status',$lessonStatus)
                    ->where("lesson_hour.teacher_id",$param['teacher_id'])
                    ->select(['lesson_hour.customer_id','lesson_hour.lesson_status','lesson_hour.lessons'])->get();

                foreach ($result['data'] as $key => $item)
                {
                    $result['data'][$key]['check_lessons'] = 0;
                    $result['data'][$key]['complete_lessons'] = 0;

                    foreach ($lessonHours as $lessonHour)
                    {
                        $lessonHour['lesson_status'] = LessonHourController::LESSON_STATUS_2 ? $result['data'][$key]['check_lessons'] += $lessonHour['lessons'] : $result['data'][$key]['complete_lessons'] += $lessonHour['lessons'];
                    }
                }
            }
        }
        else
        {
            $result = Customer::query()
                ->where($where)
                ->where("customer.username","like","%{$param['user_name']}%")
                ->select(['customer.id as id','customer.username as customer_name','customer.phone','customer.created_at',DB::raw('SUM(tl_customer_lesson.lessons) as last_lessons')])
                ->join("customer_lesson","customer.id","=","customer_lesson.customer_id","left")->groupBy("customer.id")
                ->paginate($param['limit'] ?? 10 ,['*'] ,'' ,$param['page'])->toArray();
            $customerIds = [];
            if (!empty($result['data']))
            {
                foreach ($result['data'] as $key => $value)
                {
                    $customerIds[] = $value['id'];
                    $result['data'][$key]['customer_number'] = 100 . $value['id'];
                    $result['data'][$key]['is_customer'] = true;
                }

                $lessonStatus= [LessonHourController::LESSON_STATUS_2,LessonHourController::LESSON_STATUS_5];
                $lessonHours = LessonHour::query()
                    ->whereIn("lesson_hour.customer_id",$customerIds)
                    ->whereIn('lesson_hour.lesson_status',$lessonStatus)
                    ->select(['lesson_hour.customer_id','lesson_hour.lesson_status','lesson_hour.lessons'])->get();

                $customerLessons = CustomerLesson::query()
                    ->whereIn("customer_lesson.customer_id",$customerIds)
                    ->select(['customer_lesson.customer_id','customer_lesson.teacher_id','customer_lesson.lessons','teacher.name as teacher_name'])
                    ->join("teacher","customer_lesson.teacher_id","=","teacher.id","left")
                    ->get();

                foreach ($result['data'] as $key => $item)
                {
                    $result['data'][$key]['check_lessons'] = 0;
                    $result['data'][$key]['complete_lessons'] = 0;

                    $child = [];
                    foreach ($customerLessons as $customerLesson)
                    {
                        if ($item['id'] == $customerLesson['customer_id'])
                        {
                            $child[$customerLesson['teacher_id']]['customer_name'] = $customerLesson['teacher_name'];
                            $child[$customerLesson['teacher_id']]['last_lessons'] = $customerLesson['lessons'];
                            $child[$customerLesson['teacher_id']]['check_lessons'] = 0;
                            $child[$customerLesson['teacher_id']]['complete_lessons'] = 0;
                        }
                    }

                    foreach ($lessonHours as $lessonHour)
                    {
                        if ($item['id'] == $lessonHour['customer_id'])
                        {
                            $lessonHour['lesson_status'] = LessonHourController::LESSON_STATUS_2 ? $result['data'][$key]['check_lessons'] += $lessonHour['lessons'] : $result['data'][$key]['complete_lessons'] += $lessonHour['lessons'];

                            if (isset($child[$lessonHour['teacher_id']]))
                            {
                                $child[$lessonHour['teacher_id']]['check_lessons'] += $lessonHour['lesson_status'] == LessonHourController::LESSON_STATUS_2 ? $lessonHour['lessons'] : 0;
                                $child[$lessonHour['teacher_id']]['complete_lessons'] += $lessonHour['lesson_status'] == LessonHourController::LESSON_STATUS_5 ? $lessonHour['lessons'] : 0;
                            }
                        }
                    }

                    $result['data'][$key]['children'] = array_values($child);
                }
            }
        }

        return $result;
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function add(Request $request)
    {
        $params = $request->all();
        if(empty($params['phone']) || empty($params['username'])) throw new FailedException("请填写完整用户信息");

        $customer = Customer::query()->where(['phone' => $params['phone'], 'status' => 1])->first();
        if($customer) throw new FailedException("用户手机号已存在");

        $data['username'] = $params['username'];
        $data['phone'] = $params['phone'];

        return $this->model->storeBy($data);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request)
    {
        $params = $request->all();
        if(empty($params['id']) || empty($params['phone']) || empty($params['username'])) throw new FailedException("请填写完整用户信息");

        $customer = Customer::query()->where(['phone' => $params['phone'], 'status' => 1])->first();
        if($customer && $customer['id'] != $params['id']) throw new FailedException("用户手机号已存在");

        $data['username'] = $params['username'];
        $data['phone'] = $params['phone'];

        return $this->model->updateBy($params['id'], $data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function delete(Request $request)
    {
        $id = $request->get('id');
        $customer = Customer::query()->where(['id' => $id, 'status' => 1])->first();
        if(!$customer) throw new FailedException("用户不存在");

        return $this->model->updateBy($id, ['status' => 2]);
    }


    public function getArrKey($hours)
    {
        $result = [];
        foreach ($hours as $hour)
        {
            $result[$hour['customer_id']."_".$hour['teacher_id']] = $hour['lessons'];
        }
        return $result;
    }
}
